<?php
/**
 *
 * User: JSparrow
 * DateTime: 2016/11/22 15:15
 * Created by PhpStorm.
 */

namespace app\modules\admin\models\form;


use app\models\Admin;
use app\models\Profile;
use app\modules\admin\components\BaseForm;
use Yii;
use yii\base\Exception;

class AdminForm extends BaseForm
{
    const SCENARIO_LOGIN = 'login';

    public $username;
    public $email;
    public $mobile;
    public $password;
    public $repassword;
    public $verifyCode;

    private $_admin = false;

    public function rules()
    {
        return [
            [['username', 'email', 'mobile', 'password', 'verifyCode', 'repassword'], 'required'],
            ['email', 'email'],
            [['mobile'], 'match', 'pattern'=>'/^1[3|4|5|7|8]{1}[0-9]{9}$/i', 'message'=>'手机号码格式不正确'],
            ['verifyCode', 'captcha', 'captchaAction' => '/admin/default/captcha'],
            ['password', 'validatepassword', 'on'=>self::SCENARIO_LOGIN],
            [['password', 'repassword'], 'string', 'length'=>[6,32]],
            ['password', 'compare', 'compareAttribute'=>'repassword', 'skipOnEmpty'=>true, 'on'=>[self::SCENARIO_CREATE, self::SCENARIO_UPDATE]],
            ['repassword', 'compare', 'compareAttribute'=>'password']
        ];
    }

    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'email' => '电子邮箱',
            'mobile' => '手机号',
            'password' => '密码',
            'repassword' => '检验密码',
            'verifyCode' => '验证码',
        ];
    }

    public function scenarios()
    {
        return array_merge(parent::scenarios(), [
            self::SCENARIO_LOGIN => ['email', 'password', 'verifyCode'],
            self::SCENARIO_CREATE => ['username', 'email', 'mobile', 'password', 'repassword'],
            self::SCENARIO_UPDATE => ['username', 'email', 'mobile'],
        ]);
    }

    public function validatepassword($attribute, $params) {
        if(!$this->hasErrors() && $this->scenario===self::SCENARIO_LOGIN) {
            $admin = $this->getAdmin();
            if (!$admin || !$admin->validatePassword($this->password)) {
                $this->addError($attribute, '用户名或者密码错误！');
            }
        }
    }

    private function getAdmin()
    {
        if($this->_admin === false) {
            $this->_admin = Admin::findByEmail($this->email);
        }
        return $this->_admin;
    }

    public function create()
    {
        if($this->validate()) {
            $trans = Yii::$app->db->beginTransaction();
            $admin = new Admin();
            try {
                $admin->setAttributes($this->getAttributes());
                $admin->status = Admin::STATUS_ACTIVED;
                $admin->password_hash = Yii::$app->security->generatePasswordHash($this->password);
                $admin->created_at = time();
                $admin->updated_at = time();
                $admin->profile_id = $this->createProfile()->id;
                if($admin->save()) {
                    $trans->commit();
                    return true;
                }

                $error = '';
                foreach ($admin->errors as $es) {
                    foreach ($es as $e) {
                        $error .= ($e."<br />");
                    }
                }
                Yii::$app->session->setFlash('error', $error);
                return false;
            } catch (Exception $e) {
                Yii::$app->session->setFlash('error', $e->getMessage());
                $trans->rollBack();
                return false;
            }
        } else {
            $error = '';
            foreach ($this->errors as $es) {
                foreach ($es as $e) {
                    $error .= ($e."<br />");
                }
            }
            Yii::$app->session->setFlash('error', $error);
            return false;
        }

    }

    public function update()
    {
        if($this->validate()) {

        } else {
            return false;
        }

    }

    /**
     * 说明: 管理员登录处理
     * @return bool
     */
    public function login()
    {
        if($this->validate()) {
            return Yii::$app->user->login($this->getAdmin());
        }
        return false;
    }

    private function createProfile()
    {
        $profile = new Profile();
        $profile->nickname = $this->username;
        $profile->email = $this->email;
        $profile->mobile = $this->mobile;
        if($profile->save()) {
            return $profile;
        } else {
            throw new Exception('用户档案建立失败！');
        }
    }


}